﻿using System;
using System.Collections;
using System.IO;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Configuration;
using CRMEntity;
using CRMFramework;

using Newtonsoft.Json;
using MessageMedia;
using MessageMedia.Common;
using MessageMedia.Diagnostics;
using MessageMedia.Events;
using MessageMedia.Exceptions;
using MessageMedia.Gateway.ActionResult;
using MessageMedia.SMS;


namespace CRMBiz
{
    public static class ContactFollowUpHandler
    {
        static string loanEmailAccount = null;
        static string bussinessEmailAccount = null;
        static string loanEmailAccountPassword = null;
        static string bussinessEmailAccountPassword = null;

        static string personalEmailSubject = null;
        static string businessEmailSubject = null;
        static string personalEmailContent = null;
        static string businessEmailContent = null;

        static string smsUser = null;
        static string smsPassword = null;

        static string personalSMSContent = null;
        static string businessSMSContent = null;

        /// <summary>
        /// Set up default value for sending following up email.
        /// </summary>
        public static void Setup()
        {
            loanEmailAccount = ConfigurationManager.AppSettings["personalLoanEmailAccount"];
            bussinessEmailAccount = ConfigurationManager.AppSettings["bussinessLoanEmailAccount"];
            loanEmailAccountPassword = GetEmailAccountPassword(loanEmailAccount);
            bussinessEmailAccountPassword = GetEmailAccountPassword(bussinessEmailAccount);

            personalEmailContent = GetEmailTemplate("sp_GetFollowUpEmailContent", out businessEmailContent, out personalEmailSubject, out businessEmailSubject);
            personalSMSContent = GetSMSTemplate("sp_GetFollowUpSMSContent", out businessSMSContent);

            smsUser = ConfigurationManager.AppSettings["SMSUserName"];
            smsPassword = ConfigurationManager.AppSettings["SMSPassword"];
        }
        /// <summary>
        /// Get follow up contacts list
        /// </summary>
        /// <returns></returns>
        public static List<FollowUpContact> GetFollowUpList()
        {
            DataTable dt=null;
            FollowUpContact c = null;
            List<FollowUpContact> followUpList = new List<FollowUpContact>();
            dt = DBhelper.ExecuteDatasetSP("sp_GetFollowUpContactList").Tables[0];

            foreach (DataRow dr in dt.Rows)
            {
                c = new FollowUpContact();
                c.ApplicationId = Convert.ToInt32(dr["ApplicationId"].ToString().Trim());
                c.ContactId = Convert.ToInt32(dr["ContactId"].ToString().Trim());
                c.EmailAddress = dr["EmailAddress"].ToString();
                c.MobileNumber = dr["MobileNumber"].ToString().Replace(" ", string.Empty);
                c.FirstName = dr["FirstName"].ToString();
                c.MiddleName = dr["MiddleName"].ToString();
                c.Surname = dr["Surname"].ToString();
                c.IsBusiness = Convert.ToInt16(dr["isBusiness"].ToString().Trim()) == 1;
                followUpList.Add(c);
            }

            return followUpList;
        }
        /// <summary>
        /// Send Follow up Email to client email address
        /// </summary>
        /// <param name="contactFollowUpList"></param>
        public static void SendEmail(FollowUpContact c)
        {
            string sendFrom = loanEmailAccount;
            string emailContent = personalEmailContent;
            string smsContent=personalSMSContent;
            string emailSubject = personalEmailSubject;
            string emailAccountPassword = loanEmailAccountPassword;
           
            if (c.IsBusiness)
            {
                sendFrom = bussinessEmailAccount;
                emailContent = businessEmailContent;
                smsContent=businessSMSContent;
                emailSubject = businessEmailSubject;
                emailAccountPassword = bussinessEmailAccountPassword;
            }

            string decodeEmailContent=HttpUtility.UrlDecode(emailContent).Replace("%FirstName (Client)%", c.FullName);
            ClientProfileHandler.SendEmail(sendFrom, emailAccountPassword, c.EmailAddress, "", "", emailSubject, decodeEmailContent);
            string emailContentWithName = emailContent.Replace("%25FirstName%20(Client)%25", c.FirstName);
            UpdateApplicationStatus(c, emailContentWithName, false);
        }


        /// <summary>
        /// Send sms to client mobile number
        /// </summary>
        public static void SendMessage(FollowUpContact c)
        {
            string smsContent = personalSMSContent;
            string mobileNumber = c.MobileNumber.Trim().Replace(" ",string.Empty);

            if (c.IsBusiness)
            {
                smsContent = businessSMSContent;
            }

            string messageContent = smsContent.Replace("%FirstName (Client)%", c.FullName);
            SmsHelper.SendSMSFromConsole(mobileNumber, messageContent, smsUser, smsPassword);
            UpdateApplicationStatus(c, messageContent, true);
        }

   
        /// <summary>
        /// Update application status after sending follow up email is successful
        /// </summary>
        /// <param name="applicationId"></param>
        private static void UpdateApplicationStatus(FollowUpContact c,string emailContent,bool isSMS)
        {
            string currentDate=DateTime.Now.ToString("yyyy-MM-dd");
            string currentTime = DateTime.Now.ToString("HH:mm:ss");
            string actionTitle = isSMS ? "SMS Sent" : "Email Sent";
            bool isRecordHistory = ClientProfileHandler.UpdateHistoryData(c.ApplicationId, currentDate, currentTime, actionTitle, "System", emailContent);
            string queryString = "update crm_application set app_result='1.3 Await documents - NO Follow (Case Hold)', editdate='" + currentDate + " " + currentTime + "' where app_id='" + c.ApplicationId + "'";
            DBhelper.ExecuteNonQuery(queryString);
        }
        /// <summary>
        /// Get password from email account.
        /// </summary>
        /// <returns></returns>
        private static string GetEmailAccountPassword(string emailAccount)
        {
            string sql = "SELECT Password ,EmailId FROM `crm_emailaccount` WHERE EmailId like '%"+emailAccount +"%'";
            DataTable dt = DBhelper.ExecuteDataset(sql).Tables[0];
            return dt.Rows[0]["Password"].ToString();
        }
        /// <summary>
        /// Get follow up email content and subject title
        /// </summary>
        /// <param name="storeProcedureName"></param>
        /// <param name="emailSubject"></param>
        /// <returns></returns>
        private static string GetEmailTemplate(string storeProcedureName, out string businessEmailContent, out string personalEmailSubject, out string businessEmailSubject)
        {
            string personalEmailContent = null;
            personalEmailSubject = string.Empty;
            businessEmailSubject = string.Empty;
            businessEmailContent = string.Empty;

            DataTable dt = DBhelper.ExecuteDatasetSP(storeProcedureName).Tables[0];
            personalEmailContent = dt.Rows[0]["TemplateFormat"].ToString();
            personalEmailSubject = dt.Rows[0]["emailSubject"].ToString();
            businessEmailContent = dt.Rows[1]["TemplateFormat"].ToString();
            businessEmailSubject = dt.Rows[1]["emailSubject"].ToString();

            return personalEmailContent;
        }
        /// <summary>
        /// Get SMS Template content
        /// </summary>
        /// <param name="storeProcedureName"></param>
        /// <param name="businessSMSContent"></param>
        /// <returns></returns>
        private static string GetSMSTemplate(string storeProcedureName, out string businessSMSContent)
        {
            string personalSMSContent = null;
            businessSMSContent = string.Empty;

            DataTable dt = DBhelper.ExecuteDatasetSP(storeProcedureName).Tables[0];
            personalSMSContent = dt.Rows[0]["TemplateFormat"].ToString();
            businessSMSContent = dt.Rows[1]["TemplateFormat"].ToString();

            return personalSMSContent;
        }
      
    }
}
